﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

using vroom.db.model;
using System.Diagnostics;
using vroom.db.model;

namespace vroom.db.model.client
{
	class Program
	{
		static void Main(string[] args)
		{
			using (ReportingEntities entities = new ReportingEntities())
			{
				var results = entities.TRPL_Position.Where(p => p.Effective_Date == new DateTime(2014, 11, 21))
													.ToArray<TRPL_Position>();


				Stopwatch sw = new Stopwatch();

				sw.Reset();
				sw.Start();
				byte[] comprsdStream = GetCompressedBytes(results);
				sw.Stop();
				Console.WriteLine("Compress: " + (sw.ElapsedMilliseconds / 1000));


				sw.Reset();
				sw.Start();
				TRPL_Position[] resultsAfter = GetObjectFromCompressedBytes<TRPL_Position[]>(comprsdStream);
				sw.Stop();
				Console.WriteLine("De-Compress: " + (sw.ElapsedMilliseconds / 1000));

				
			} 
		}


		private static byte[] GetCompressedBytes(object obj)
		{
			using (var memoryStream = new System.IO.MemoryStream())
			{
				using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress))
				{
					BinaryFormatter binaryFormatter = new BinaryFormatter();
					binaryFormatter.Serialize(gZipStream, obj);
				}
				return memoryStream.ToArray();
			}
		}


		private static T GetObjectFromCompressedBytes<T>(byte[] compressed)
		{
			object desirialized;

			using (var memoryStream = new System.IO.MemoryStream(compressed))
			{
				using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
				{
					BinaryFormatter binaryFormatter = new BinaryFormatter();
					desirialized = (T) binaryFormatter.Deserialize(gZipStream);
				}
				return (T) desirialized;
			}
		}
	}
}
